using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Read.API.Applications.Commands.suppliers;

namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.suppliers
{
    /// <summary>
    /// 获取供应商列表查询处理器
    /// </summary>
    public class GetSuppliersQueryHandler : IRequestHandler<GetSuppliersQuery, ApiPaging<SupplierListDto>>
    {
        private readonly IBaseRepository<Supplier> _supplierRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetSuppliersQueryHandler> _logger;

        public GetSuppliersQueryHandler(
            IBaseRepository<Supplier> supplierRepository,
            IMapper mapper,
            ILogger<GetSuppliersQueryHandler> logger)
        {
            _supplierRepository = supplierRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取供应商列表查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页查询结果</returns>
        public async Task<ApiPaging<SupplierListDto>> Handle(GetSuppliersQuery request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询供应商列表，页码: {PageIndex}, 每页大小: {PageSize}", 
                    request.PageIndex, request.PageSize);

                // 构建查询条件
                var query = _supplierRepository.GetAll()
                    .Where(s => !s.IsDeleted); // 排除已删除的记录

                // 应用筛选条件
                query = ApplyFilters(query, request);

                // 获取总数量
                var totalCount = await query.CountAsync(cancellationToken);

                // 计算总页数
                var pageCount = (int)Math.Ceiling((double)totalCount / request.PageSize);

                // 分页查询
                var suppliers = await query
                    .OrderByDescending(s => s.CreatedTime) // 按创建时间倒序排列
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 映射到DTO
                var supplierDtos = _mapper.Map<List<SupplierListDto>>(suppliers);

                _logger.LogInformation("成功查询供应商列表，总数量: {TotalCount}, 当前页数量: {CurrentPageCount}", 
                    totalCount, supplierDtos.Count);

                return new ApiPaging<SupplierListDto>
                {
                    code = ResultEnumCode.Ok,
                    message = "查询成功",
                    data = default,
                    TotalCount = totalCount,
                    PageCount = pageCount,
                    PageData = supplierDtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询供应商列表时发生异常");
                
                return new ApiPaging<SupplierListDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"查询供应商列表时发生异常: {ex.Message}",
                    data = default,
                    TotalCount = 0,
                    PageCount = 0,
                    PageData = new List<SupplierListDto>()
                };
            }
        }

        /// <summary>
        /// 应用筛选条件
        /// </summary>
        /// <param name="query">查询对象</param>
        /// <param name="request">查询请求</param>
        /// <returns>应用筛选条件后的查询对象</returns>
        private IQueryable<Supplier> ApplyFilters(IQueryable<Supplier> query, GetSuppliersQuery request)
        {
            // 供应商编号模糊查询
            if (!string.IsNullOrWhiteSpace(request.SupplierCode))
            {
                query = query.Where(s => s.SupplierCode.Contains(request.SupplierCode));
            }

            // 供应商名称模糊查询
            if (!string.IsNullOrWhiteSpace(request.SupplierName))
            {
                query = query.Where(s => s.SupplierName.Contains(request.SupplierName));
            }

            // 供应商类型精确查询
            if (!string.IsNullOrWhiteSpace(request.SupplierType))
            {
                query = query.Where(s => s.SupplierType == request.SupplierType);
            }

            // 负责人电话模糊查询
            if (!string.IsNullOrWhiteSpace(request.ContactPhone))
            {
                query = query.Where(s => s.ContactPhone != null && s.ContactPhone.Contains(request.ContactPhone));
            }


            // 所属市场模糊查询
            if (!string.IsNullOrWhiteSpace(request.AffiliatedMarket))
            {
                query = query.Where(s => s.AffiliatedMarket != null && s.AffiliatedMarket.Contains(request.AffiliatedMarket));
            }

            // 服务人员模糊查询
            if (!string.IsNullOrWhiteSpace(request.ServicePersonnel))
            {
                query = query.Where(s => s.ServicePersonnel != null && s.ServicePersonnel.Contains(request.ServicePersonnel));
            }

            // 使用状态精确查询
            if (!string.IsNullOrWhiteSpace(request.Status))
            {
                query = query.Where(s => s.Status == request.Status);
            }

            // 是否归档
            if (request.IsArchived.HasValue)
            {
                query = query.Where(s => s.IsArchived == request.IsArchived.Value);
            }

            return query;
        }
    }
}